package com.jsh.erp.service.contract;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.Contract;
import com.jsh.erp.datasource.entities.ContractExample;
import com.jsh.erp.datasource.entities.User;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.accountHead.AccountHeadService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class ContractService {
    private Logger logger = LoggerFactory.getLogger(ContractService.class);

    @Resource
    private ContractMapper contractMapper;

    @Resource
    private ContractMapperEx contractMapperEx;
    @Resource
    private LogService logService;
    @Resource
    private UserService userService;
    @Resource
    private DepotHeadService depotHeadService;

    public Contract getContract(long id)throws Exception {
        Contract result=null;
        try{
            result=contractMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<Contract> getContractListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<Contract> list = new ArrayList<>();
        try{
            ContractExample example = new ContractExample();
            example.createCriteria().andIdIn(idList);
            list = contractMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Contract> getContract()throws Exception {
        ContractExample example = new ContractExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Contract> list=null;
        try{
            list=contractMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Contract> select(String name, String type, String projectId, String sn , String roleType, int offset, int rows) throws Exception{
        List<Contract> resList = new ArrayList<Contract>();
        try{
            String [] creatorArray = depotHeadService.getCreatorArray(roleType);
            List<Contract> list = contractMapperEx.selectByConditionContract(name, type, projectId, sn,  creatorArray, offset, rows);
            for(Contract s : list) {
                resList.add(s);
            }
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return resList;
    }

    public Long countContract(String name, String type, String projectId, String sn, String roleType) throws Exception{
        Long result=null;
        try{
            String [] creatorArray = depotHeadService.getCreatorArray(roleType);
            result=contractMapperEx.countsByContract(name, type, projectId, sn, creatorArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertContract(JSONObject obj, HttpServletRequest request)throws Exception {
        Contract contract = JSONObject.parseObject(obj.toJSONString(), Contract.class);
        int result=0;
        try{
            contract.setEnabled(true);
            User userInfo=userService.getCurrentUser();
            contract.setCreator(userInfo==null?null:userInfo.getId());
            result=contractMapper.insertSelective(contract);

            logService.insertLog("合同",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(contract.getName()).toString(),request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateContract(JSONObject obj, HttpServletRequest request)throws Exception {
        Contract contact = JSONObject.parseObject(obj.toJSONString(), Contract.class);
        int result=0;
        try{
            result=contractMapper.updateByPrimaryKeySelective(contact);
            logService.insertLog("合同",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(contact.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteContract(Long id, HttpServletRequest request)throws Exception {
        return batchDeleteContractByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteContract(String ids, HttpServletRequest request) throws Exception{
        return batchDeleteContractByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteContractByIds(String ids)throws Exception {
        int result=0;
        String [] idArray=ids.split(",");

        //记录日志
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<Contract> list = getContractListByIds(ids);
        for(Contract project: list){
            sb.append("[").append(project.getName()).append("]");
        }
        logService.insertLog("合同", sb.toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        User userInfo=userService.getCurrentUser();
        //校验通过执行删除操作
        try{
            result = contractMapperEx.batchDeleteContractByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name)throws Exception {
        ContractExample example = new ContractExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Contract> list=null;
        try{
            list= contractMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list==null?0:list.size();
    }

    public int checkIsNameAndTypeExist(Long id, String name, String type)throws Exception {
        name = name == null? "": name;
        ContractExample example = new ContractExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andTypeEqualTo(type)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Contract> list=null;
        try{
            list= contractMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list==null?0:list.size();
    }

    public List<Contract> findBySelect()throws Exception {
        ContractExample example = new ContractExample();
        example.createCriteria().andEnabledEqualTo(true).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Contract> list=null;
        try{
            list = contractMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Contract> findBySelectType(String type)throws Exception {
        ContractExample example = new ContractExample();
        example.createCriteria().andTypeLike(type).andEnabledEqualTo(true).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Contract> list=null;
        try{
            list = contractMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Contract> findById(Long supplierId)throws Exception {
        ContractExample example = new ContractExample();
        example.createCriteria().andIdEqualTo(supplierId)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Contract> list=null;
        try{
            list = contractMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }



    public List<Contract> findByAll(String name, String type, String projectId, String sn) throws Exception{
        List<Contract> list=null;
        try{
            list = contractMapperEx.findByAll(name, type, projectId, sn);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public BigDecimal parseBigDecimalEx(String str)throws Exception{
        if(!StringUtil.isEmpty(str)) {
            return new BigDecimal(str);
        } else {
            return null;
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetStatus(Boolean status, String ids)throws Exception {
        logService.insertLog("合同",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ENABLED).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        List<Long> supplierIds = StringUtil.strToLongList(ids);
        Contract contract = new Contract();
        contract.setEnabled(status);
        ContractExample example = new ContractExample();
        example.createCriteria().andIdIn(supplierIds);
        int result=0;
        try{
            result = contractMapper.updateByExampleSelective(contract, example);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
}
